﻿using CommonType;
using MediatR;
using S_Gridding.Domains.FoundGridding;
using S_Gridding.Infrastructure.Interface.IRead;
using S_Gridding.Read.Api.Application.Commands;
using S_Userinfor.Domains;

namespace S_Gridding.Read.Api.Application.CommandsHanders
{
    public class GriddingShowCommandsHanders : IRequestHandler<GriddingShowCommands, PageResule<Gridding>>
    {
        private readonly IDGriddingRepository _iDGridding;

        public GriddingShowCommandsHanders(IDGriddingRepository iDGridding)
        {
            _iDGridding = iDGridding;
        }

        public async Task<PageResule<Gridding>> Handle(GriddingShowCommands request, CancellationToken cancellationToken)
        {
            var query = $" SELECT * FROM Gridding WHERE 1=1 AND IsDel !=TRUE";

            if (!string.IsNullOrEmpty(request.Grid_name))   
            {
                query += $" AND Grid_name LIKE '%{request.Grid_name}%' ";
            }
            if (request.Owning_region>0) 
            {
                query += $" AND Owning_region = {request.Owning_region}";
            }
            var tacount = await _iDGridding.SelectAsync(request.PageSize, query);

            query += $" ORDER BY ID DESC LIMIT {(request.PageIndex - 1) * request.PageSize},@PageSize;";

            var List = await _iDGridding.SelectAsync(request.PageSize, query);

            return new PageResule<Gridding>
            {
                TotalCount = tacount.Count(),
                PageCount = (int)Math.Ceiling((List.Count() * 1.0) / request.PageSize),
                Data = List,
            };
        }
    }
}
